package com.zvezda.http.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.os.Bundle;
import android.os.Message;
import android.util.Log;

/**
 * Post请求
 * 
 * @author Zvezda
 * 
 */
public class RequestHttpPostThread extends Thread
{
	/**
	 * 回调接口数据的接口
	 */
	private RequestHttpListener requestHttpListener = null;
	
	/**
	 * 路径
	 */
	private String urlPath = null;
	
	/**
	 * 请求超时时间
	 */
	private int requestTime = 15000;
	
	/**
	 * 连接超时时间
	 */
	private int connectTime = 15000;
	
	/**
	 * 标签默认为-1
	 */
	private int customTag = -1;
	
	/**
	 * 无错误
	 */
	private int errorType = HttpConst.ERROR_NO;
	
	/**
	 * httpClinet
	 */
	private DefaultHttpClient httpClient = new DefaultHttpClient();
	
	/**
	 * 参数列表
	 */
	private ArrayList<KeyValue<String, Object>> paramsList = null;
	
	/**
	 * 构造函数
	 * 
	 * @param requestHttpPostInterface
	 *            回调接口
	 * @param urlPath
	 *            地址
	 * @param paramsList
	 *            参数list
	 */
	public RequestHttpPostThread(RequestHttpListener requestHttpListener, String urlPath,
			ArrayList<KeyValue<String, Object>> paramsList)
	{
		this.requestHttpListener = requestHttpListener;
		this.urlPath = urlPath;
		this.paramsList = paramsList;
	}
	
	/**
	 * 获得请求的监听接口
	 * 
	 * @return
	 */
	public RequestHttpListener getRequestHttpListener()
	{
		return requestHttpListener;
	}
	
	/**
	 * 设置请求的监听接口
	 */
	public void setRequestHttpListener(RequestHttpListener requestHttpListener)
	{
		this.requestHttpListener = requestHttpListener;
	}
	
	/**
	 * 获得cook
	 * 
	 * @return
	 */
	public CookieStore getCookieStore()
	{
		if (httpClient != null)
		{
			return httpClient.getCookieStore();
		}
		return null;
	}
	
	/**
	 * 设置cookieStore
	 * 
	 * @param cookieStore
	 */
	public void setCookieStore(CookieStore cookieStore)
	{
		if (httpClient != null)
		{
			httpClient.setCookieStore(cookieStore);
		}
	}
	
	@Override
	public void run()
	{
		try
		{
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTime);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, requestTime);
			HttpPost httpost = new HttpPost(urlPath);
			// httpost.addHeader("Content-Type", "application/x-www-form-urlencoded");
			MultipartEntity reqEntity = new MultipartEntity();
			if (paramsList != null)
			{
				for (KeyValue<String, Object> keyValue : paramsList)
				{
					String key = keyValue.getKey();
					Object value = keyValue.getValue();
					if (value instanceof StringBody)
					{
						reqEntity.addPart(key, (StringBody) value);
					}
					else if (value instanceof FileBody)
					{
						reqEntity.addPart(key, (FileBody) value);
					}
				}
			}
			// 设置请求
			httpost.setEntity(reqEntity);
			// 执行
			HttpResponse response = httpClient.execute(httpost);
			int resultCode = response.getStatusLine().getStatusCode();
			switch (resultCode)
			{
				case HttpStatus.SC_OK:// 请求成功
					HttpEntity entity = response.getEntity();
					// 显示内容
					if (entity != null)
					{
						InputStream is = entity.getContent();
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						byte[] buffer = new byte[1024];
						int len = 0;
						while ((len = is.read(buffer)) != -1)
						{
							baos.write(buffer, 0, len);
						}
						baos.flush();
						baos.close();
						is.close();
						
						// String info = EntityUtils.toString(entity);
						System.out.println("回复-------->" + new String(baos.toByteArray(), "utf-8"));
						sendMsg(HttpConst.ACTION_SUCCESS, baos.toByteArray());
						entity.consumeContent();
					}
					else
					{
						sendMsg(HttpConst.ACTION_FAIL, null);
					}
					break;
				default:
					Log.e(HttpConst.HTTP_LOG, getClass().getSimpleName() + "  Request Lose--------------------->"
							+ resultCode);
					errorType = HttpConst.ERROE_RESPONSE;
					sendMsg(HttpConst.ACTION_FAIL, null);
					break;
			}
		}
		catch (SocketTimeoutException se)
		{
			Log.e(HttpConst.HTTP_LOG,
					getClass().getSimpleName() + "  SocketTimeoutException--------------------->" + se.toString());
			errorType = HttpConst.ERROR_TIME_OUT;
			sendMsg(HttpConst.ACTION_FAIL, null);
		}
		catch (IOException e)
		{
			Log.e(HttpConst.HTTP_LOG, getClass().getSimpleName() + "  IOException--------------------->" + e.toString());
			errorType = HttpConst.ERROR_IO;
			sendMsg(HttpConst.ACTION_FAIL, null);
		}
		catch (Exception e)
		{
			Log.e(HttpConst.HTTP_LOG, getClass().getSimpleName() + "  Exception--------------------->" + e.toString());
			errorType = HttpConst.ERROR_OTHER;
			sendMsg(HttpConst.ACTION_FAIL, null);
		}
	}
	
	/**
	 * 返回读取数据的结果
	 * 
	 * @param result
	 * @param dataArr
	 */
	private void sendMsg(int result, byte[] dataArr)
	{
		if (requestHttpListener != null)
		{
			Bundle bundle = new Bundle();
			bundle.putString(HttpConst.FILE_URL, urlPath);
			bundle.putInt(HttpConst.ACTION_RESULT, result);
			bundle.putInt(HttpConst.ERROR_TYPE, errorType);
			bundle.putInt(HttpConst.CUSTOM_TAG, customTag);
			if (dataArr != null)
			{
				bundle.putByteArray(HttpConst.DATA_ARR, dataArr);
			}
			Message msg = new Message();
			msg.setData(bundle);
			requestHttpListener.requestHttp(msg);
		}
	}
	
	/**
	 * 获得请求超时的时间
	 * 
	 * @return
	 */
	public int getRequestTime()
	{
		return requestTime;
	}
	
	/**
	 * 设置请求超时的时间
	 * 
	 * @param requestTime
	 */
	public void setRequestTime(int requestTime)
	{
		this.requestTime = requestTime;
	}
	
	/**
	 * 获得连接超时的时间
	 * 
	 * @return
	 */
	public int getConnectTime()
	{
		return connectTime;
	}
	
	/**
	 * 设置连接超时的时间
	 * 
	 * @param connectTime
	 */
	public void setConnectTime(int connectTime)
	{
		this.connectTime = connectTime;
	}
	
	/**
	 * 获得自定义标签
	 * 
	 * @return
	 */
	public int getTag()
	{
		return customTag;
	}
	
	/**
	 * 设置自定义标签
	 * 
	 * @param tag
	 */
	public void setTag(int tag)
	{
		this.customTag = tag;
	}
}
